<template>
  <div class="staff-management">
    <div class="page-header">
      <h2 class="page-title">护理人员管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加人员
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="searchForm.idCard" placeholder="请输入身份证号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="searchForm.position" placeholder="请选择职位" clearable style="width: 150px">
            <el-option label="护士" value="护士" />
            <el-option label="护工" value="护工" />
            <el-option label="医生" value="医生" />
            <el-option label="营养师" value="营养师" />
            <el-option label="康复师" value="康复师" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="在职" value="ACTIVE" />
            <el-option label="离职" value="INACTIVE" />
            <el-option label="请假" value="ON_LEAVE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table :data="staffList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatarUrl">
              <span>{{ row.name?.charAt(0) || '?' }}</span>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="180" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === 'M' ? 'primary' : 'danger'">
              {{ row.gender === 'M' ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="position" label="职位" width="120">
          <template #default="{ row }">
            <el-tag :type="getPositionColor(row.position)">
              {{ row.position }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="department" label="科室" />
        <el-table-column prop="experience" label="工作经验" width="100" />
        <el-table-column label="证书" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.certificates" type="info" size="small">
              {{ getCertificateCount(row.certificates) }}个
            </el-tag>
            <span v-else class="text-gray-400">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hireDate" label="入职日期" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="formData.idCard" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio value="M">男</el-radio>
                <el-radio value="F">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="formData.age" :min="18" :max="65" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-select v-model="formData.position" placeholder="请选择职位">
                <el-option label="护士" value="护士" />
                <el-option label="护工" value="护工" />
                <el-option label="医生" value="医生" />
                <el-option label="营养师" value="营养师" />
                <el-option label="康复师" value="康复师" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室" prop="department">
              <el-input v-model="formData.department" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作经验" prop="experience">
              <el-input v-model="formData.experience" placeholder="如：3年" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker
                v-model="formData.hireDate"
                type="date"
                placeholder="选择入职日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态">
                <el-option label="在职" value="在职" />
                <el-option label="离职" value="离职" />
                <el-option label="请假" value="请假" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="住址">
          <el-input v-model="formData.address" type="textarea" rows="2" />
        </el-form-item>
        
        <el-form-item label="专业技能">
          <el-input v-model="formData.skills" type="textarea" rows="3" />
        </el-form-item>
        
        <el-form-item label="头像">
          <div style="display: flex; align-items: center; gap: 15px;">
            <el-avatar :size="60" :src="formData.avatarUrl">
              <span>{{ formData.name?.charAt(0) || '?' }}</span>
            </el-avatar>
            <div>
              <div style="margin-bottom: 10px;">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="handleAvatarUpload"
                  accept="image/*"
                >
                  <el-button size="small" type="primary">上传头像</el-button>
                </el-upload>
                <el-button size="small" @click="showAvatarSelector = true" style="margin-left: 10px;">选择预设</el-button>
              </div>
              <div style="color: #999; font-size: 12px;">
                支持 jpg、png 格式，大小不超过 2MB
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="证书信息">
          <el-input v-model="formData.certificates" type="textarea" rows="2" placeholder="多个证书请用逗号分隔，如：护士执业证,康复治疗师证" />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input v-model="formData.notes" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="人员详情" width="600px">
      <div style="text-align: center; margin-bottom: 20px;">
        <el-avatar :size="80" :src="viewData.avatarUrl">
          <span style="font-size: 32px;">{{ viewData.name?.charAt(0) || '?' }}</span>
        </el-avatar>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="身份证号">{{ viewData.idCard }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ viewData.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag :type="viewData.gender === 'M' ? 'primary' : 'danger'">
            {{ viewData.gender === 'M' ? '男' : '女' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="年龄">{{ viewData.age }}岁</el-descriptions-item>
        <el-descriptions-item label="职位">
          <el-tag :type="getPositionColor(viewData.position)">
            {{ viewData.position }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="科室">{{ viewData.department }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ viewData.phone }}</el-descriptions-item>
        <el-descriptions-item label="工作经验">{{ viewData.experience }}</el-descriptions-item>
        <el-descriptions-item label="入职日期">{{ viewData.hireDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(viewData.status)">
            {{ getStatusText(viewData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="住址" :span="2">{{ viewData.address }}</el-descriptions-item>
        <el-descriptions-item label="专业技能" :span="2">{{ viewData.skills }}</el-descriptions-item>
        <el-descriptions-item label="证书信息" :span="2">
          <div v-if="viewData.certificates">
            <el-tag 
              v-for="(cert, index) in viewData.certificates.split(',')" 
              :key="index" 
              type="info" 
              size="small"
              style="margin-right: 8px; margin-bottom: 4px;"
            >
              {{ cert.trim() }}
            </el-tag>
          </div>
          <span v-else class="text-gray-400">无</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewData.notes || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 预设头像选择对话框 -->
    <el-dialog v-model="showAvatarSelector" title="选择预设头像" width="500px">
      <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; text-align: center;">
        <div 
          v-for="(avatar, index) in presetAvatars" 
          :key="index"
          @click="selectPresetAvatar(avatar.url)"
          style="cursor: pointer; padding: 10px; border: 2px solid transparent; border-radius: 8px;"
          :style="{ borderColor: formData.avatarUrl === avatar.url ? '#409EFF' : 'transparent' }"
        >
          <el-avatar :size="60" :src="avatar.url">
            <span>{{ avatar.name.charAt(0) }}</span>
          </el-avatar>
          <div style="margin-top: 5px; font-size: 12px;">{{ avatar.name }}</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showAvatarSelector = false">取消</el-button>
        <el-button type="primary" @click="showAvatarSelector = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const staffList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  idCard: '',
  position: '',
  status: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const showAvatarSelector = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const formRef = ref()
const formData = reactive({
  id: null,
  idCard: '',
  name: '',
  gender: 'M',
  age: 25,
  position: '',
  department: '',
  phone: '',
  experience: '',
  hireDate: '',
  status: '在职',
  address: '',
  skills: '',
  notes: '',
  avatarUrl: '',
  certificates: ''
})

// 查看数据
const viewData = ref<any>({})

// 表单验证规则
const formRules = {
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请输入科室', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  experience: [
    { required: true, message: '请输入工作经验', trigger: 'blur' }
  ],
  hireDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 状态映射函数（后端到前端）
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': '在职',
    'INACTIVE': '离职',
    'ON_LEAVE': '请假'
  }
  return statusMap[status] || status
}

// 表单状态映射函数（前端到后端）
const getFormStatusValue = (status: string) => {
  const statusMap: Record<string, string> = {
    '在职': 'ACTIVE',
    '离职': 'INACTIVE',
    '请假': 'ON_LEAVE'
  }
  return statusMap[status] || status
}

// 性别映射函数（后端到前端）
const getGenderText = (gender: string) => {
  const genderMap: Record<string, string> = {
    'M': '男',
    'F': '女'
  }
  return genderMap[gender] || gender
}

// 获取职位颜色
const getPositionColor = (position: string) => {
  const colorMap: { [key: string]: string } = {
    '护士': 'primary',
    '护工': 'success',
    '医生': 'danger',
    '营养师': 'warning',
    '康复师': 'info'
  }
  return colorMap[position] || 'default'
}

// 获取职位标签
const getPositionLabel = (position: string) => {
  return position || '未知'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': '在职',
    'INACTIVE': '离职',
    'ON_LEAVE': '请假'
  }
  return statusMap[status] || status
}

// 计算证书数量
const getCertificateCount = (certificates: string) => {
  if (!certificates || certificates.trim() === '') return 0
  return certificates.split(',').filter(cert => cert.trim() !== '').length
}

// 头像上传前的验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options: any) => {
  const file = options.file
  
  try {
    // 创建FormData对象
    const formDataUpload = new FormData()
    formDataUpload.append('file', file)
    
    // 上传到服务器
    const response = await fetch('http://localhost:8080/api/upload/avatar', {
      method: 'POST',
      body: formDataUpload
    })
    
    if (!response.ok) {
      throw new Error('上传失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 使用服务器返回的URL
      formData.avatarUrl = result.data.url
      ElMessage.success('头像上传成功！')
    } else {
      throw new Error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
    
    // 如果上传失败，使用临时URL作为降级方案
    const url = URL.createObjectURL(file)
    formData.avatarUrl = url
    ElMessage.warning('使用临时预览（刷新页面后将丢失）')
  }
}

// 预设头像数据
const presetAvatars = ref([
  { name: '默认男性', url: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
  { name: '默认女性', url: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png' },
  { name: '护士', url: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
  { name: '医生', url: 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png' },
  { name: '护工', url: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48png.png' },
  { name: '康复师', url: 'https://cube.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg' },
  { name: '营养师', url: 'https://cube.elemecdn.com/7/a0/a2bc9b32181ef68b1b80c9b6a6a1apng.png' },
  { name: '管理员', url: 'https://cube.elemecdn.com/1/a0/7929bb362c69a98d73a8fb9a4b1f0png.png' }
])

// 选择预设头像
const selectPresetAvatar = (url: string) => {
  formData.avatarUrl = url
  ElMessage.success('头像选择成功！')
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: { [key: string]: string } = {
    'ACTIVE': 'success',
    'INACTIVE': 'danger',
    'ON_LEAVE': 'warning'
  }
  return typeMap[status] || 'info'
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', (currentPage.value - 1).toString())
    params.append('size', pageSize.value.toString())
    
    // 添加搜索条件
    if (searchForm.name) {
      params.append('name', searchForm.name)
    }
    if (searchForm.idCard) {
      params.append('idCard', searchForm.idCard)
    }
    if (searchForm.position) {
      params.append('position', searchForm.position)
    }
    if (searchForm.status) {
      params.append('status', searchForm.status)
    }
    
    const response = await fetch(`http://localhost:8080/api/staff?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('获取员工列表失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      staffList.value = result.data.content.map((item: any) => ({
        id: item.id,
        idCard: item.idCard || '',
        name: item.name,
        gender: item.gender, // 直接使用后端的M/F
        age: item.age,
        position: item.position,
        department: '护理部', // 默认科室
        phone: item.phone,
        experience: `${item.workExperience || 0}年`,
        hireDate: item.hireDate,
        status: item.status, // 直接使用后端的ACTIVE/INACTIVE/ON_LEAVE
        address: item.email || '', // 暂时用邮箱字段
        skills: item.skills || '',
        notes: item.description || '',
        avatarUrl: item.avatarUrl || '', // 头像地址
        certificates: item.certificates || '' // 证书信息
      }))
      total.value = result.data.totalElements
    } else {
      ElMessage.error(result.message || '获取员工列表失败')
    }
  } catch (error) {
    console.error('加载员工列表失败:', error)
    ElMessage.error('加载员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  console.log('搜索条件:', searchForm)
  console.log('搜索状态值:', searchForm.status)
  currentPage.value = 1 // 重置到第一页
  await loadData()
}

// 重置搜索
const resetSearch = async () => {
  Object.assign(searchForm, {
    name: '',
    idCard: '',
    position: '',
    status: ''
  })
  currentPage.value = 1
  await loadData()
}

// 添加
const handleAdd = () => {
  dialogTitle.value = '添加人员'
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑人员'
  isEdit.value = true
  
  // 从显示数据映射回表单数据
  Object.assign(formData, {
    id: row.id,
    idCard: row.idCard,
    name: row.name,
    gender: row.gender, // 直接使用M/F
    age: row.age,
    position: row.position,
    department: row.department,
    phone: row.phone,
    experience: parseInt(row.experience.replace('年', '')) || 0,
    hireDate: row.hireDate ? new Date(row.hireDate) : '',
    status: getStatusText(row.status), // 转换为中文显示
    address: row.address,
    skills: row.skills,
    notes: row.notes,
    avatarUrl: row.avatarUrl,
    certificates: row.certificates
  })
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  viewData.value = row
  viewDialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
  ElMessageBox.confirm('确定要删除这个人员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await fetch(`http://localhost:8080/api/staff/${row.id}`, {
        method: 'DELETE'
      })
      
      if (!response.ok) {
        throw new Error('删除失败')
      }
      
      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 映射前端字段到后端字段
        const staffData = {
          idCard: formData.idCard,
          name: formData.name,
          gender: formData.gender,
          age: formData.age,
          position: formData.position,
          skills: formData.skills,
          workExperience: typeof formData.experience === 'string' ? parseInt(formData.experience.replace('年', '')) || 0 : formData.experience,
          phone: formData.phone,
          email: formData.address, // 暂时将地址存到邮箱字段
          hireDate: formData.hireDate ? new Date(formData.hireDate).toISOString().split('T')[0] : null,
          status: getFormStatusValue(formData.status),
          description: formData.notes,
          avatarUrl: formData.avatarUrl,
          certificates: formData.certificates
        }
        
        let response
        if (isEdit.value) {
          // 更新
          response = await fetch(`http://localhost:8080/api/staff/${formData.id}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(staffData)
          })
        } else {
          // 添加
          response = await fetch('http://localhost:8080/api/staff', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(staffData)
          })
        }
        
        if (!response.ok) {
          throw new Error(isEdit.value ? '更新失败' : '添加失败')
        }
        
        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadData()
        } else {
          ElMessage.error(result.message || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    idCard: '',
    name: '',
    gender: 'M',
    age: 25,
    position: '',
    department: '',
    phone: '',
    experience: '',
    hireDate: '',
    status: '在职',
    address: '',
    skills: '',
    notes: '',
    avatarUrl: '',
    certificates: ''
  })
}

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.staff-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>